package io;
/*version 1.1
 * bug 1: First input wrong data, second right,error happens, cannot read file
 * debug for bug 1
 */

/* version 1.2
 * by Mike
 * separate openFile() from roomDataFromFile() to facilitate testing
 */

import ioProcessor.RoomInputProcessor;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;

public class RoomInput
{
	public static FileInputStream roomInput;

	public static RoomInputProcessor cip;
	public static String rInput = "";

	static void openFile() {
		System.out.print("Please enter the path of the Room file: ");
		Scanner input = new Scanner(System.in);
		File roomFile = new File(input.next());

		try
		{
			roomInput = new FileInputStream(roomFile);
			System.out.println("File open.");
		//	fileExists = true;
			
		}catch(FileNotFoundException e)
		{
			System.out.println("The file specified is not found!\n");		
		//	fileExists = false;
		}
	}
	
	public static void roomDataFromFile()
	{		
		while (roomInput==null) {
			openFile();
		}	//while(!fileExists);

		DataInputStream roomData = null;
		BufferedReader roomReader = null;
	
		roomData = new DataInputStream(roomInput);
		roomReader = new BufferedReader(new InputStreamReader(roomData));

		if (cip==null)
			cip = new RoomInputProcessor();
		try
		{
			while((rInput = roomReader.readLine()) != null)
			{
				cip.processRoomData(rInput);
			}
		}
		catch(IOException e)
		{
			System.out.println("Exception while reading the file " + e);
		}
		
		
		try{
			roomData.close();
			roomReader.close();
			roomInput.close();
		}
		catch(IOException e){
	    	System.err.println("Error: " + e.getMessage());
		}
	}	
}
